import { app, remote } from "electron";
import path from "path";

export namespace Akaba {
    export type ProtocolPathFunc = (url: string) => string;
    export interface ProtocolConfigConfigObj {
        prefix: string;
        getPath: ProtocolPathFunc;
        type: "file";
        getURI: (url: string) => string | false ;
    }
    export interface IProtocolConfig {
        [prefix: string]: ProtocolConfigConfigObj;
    }
}

const protocolConfig: Akaba.IProtocolConfig = {
};

function getURI(protocolPrefix: string, url: string): string | false {
    const reg = new RegExp("^" + protocolPrefix + ":\\/{2,3}([^?#]+)");
    const pathnameMatch = url.match(reg);
    if (pathnameMatch) {
        return pathnameMatch[1].replace(/\\/g, "/");
    }
    return false;
}
function getPath(protocolPrefix: string, url: string) {
    const uri = getURI(protocolPrefix, url);
    if (uri) {
        const appObj = app || remote.app;
        const appPath = path.dirname(appObj.getAppPath()).replace(/\\/g, "/");
        if (uri.match(/^[A-Z]:/)) {
            return uri.replace(/\\/g, "/");
        }
        const posixIsRoot = uri.match(/^@:(.+)/);
        if (posixIsRoot) {
            return posixIsRoot[1];
        }
        return path.join(appPath, uri).replace(/\\/g, "/");
    } else {
        throw new Error(`${url} error`);
    }
}
function setProtocol(prefix: string, getPathFunc?: Akaba.ProtocolPathFunc) {
    const newProtocol: Akaba.ProtocolConfigConfigObj = {
        prefix,
        type: "file",
        getPath(url: string): string {
            if (typeof getPathFunc === "function") {
                return getPathFunc.call(newProtocol, url);
            }
            return getPath(prefix, url);
        },
        getURI(url: string): string | false {
            return getURI(prefix, url);
        },
    };
    protocolConfig[prefix] = newProtocol;
}
setProtocol("akaba");
export default protocolConfig;
